package com.thjk.bdf.preloan.web.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Cookie工具类
 *
 */
public class CookieUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(CookieUtil.class);
	
	/**
     * 根据名字获取cookie
     * @param request
     * @param name  cookie名字
     * @return
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name) {
    	Cookie cookie = null;
    	Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookieTemp : cookies) {
               if(name.equals(cookieTemp.getName())) {    	  
            	    cookie = cookieTemp;
               }
            }
        }
        return cookie;
    }
    
    /**
     * 根据名字获取cookie value
     * @param request
     * @param name  cookie名字
     * @return
     */
    public static String getCookieValueByName(HttpServletRequest request, String name) {
    	String value = null;
    	Cookie cookie = getCookieByName(request, name);
        if (null != cookie) {
        	value = cookie.getValue();
        }
        return value;
    }
      
    /** 新建保存Cookies
     * @param response
     * @param name
     * @param value
     * @param time 秒
     * @return
     */
    public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value, int time) {
    	logger.info("CookieUtil setCookie param name:{}, value:{}, time:{}.", name, value, time);
    	Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(time);
        // 将Cookie添加到Response中,使之生效
        response.addCookie(cookie); // addCookie后，如果已经存在相同名字的cookie，则最新的覆盖旧的cookie
        logger.info("CookieUtil setCookie end.");
        return response;
    }
    
    /**删除cookie
     * 
     * @param request
     * @param response
     * @param deleteKey
     */
    public static HttpServletResponse delectCookieByName(HttpServletRequest request, HttpServletResponse response, String deleteKey) {
		logger.info("CookieUtil delectCookieByName param deleteKey:{}.", deleteKey);
		Cookie cookie = getCookieByName(request, deleteKey);
	    cookie.setMaxAge(0);//设置cookie有效时间为0
	    cookie.setPath("/");//不设置存储路径
	    response.addCookie(cookie);
	    logger.info("CookieUtil delectCookieByName end.");
        return response;
    }

}
